package com.fingard.dsp.bank.directbank.abc21;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.secret.salary.FieldHiddenUtil;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class ABC21Base extends DirectBase implements ITcpClient {
    /**
     * 获取交互字符集
     *
     * @return
     */
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    public void writeCommonHeader(XmlTextWriter xmlWriter, ABC21Header bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(bankHeader.reqSeqID)) {
            throw new Exception("流水号未赋值");
        }
        if (StringHelper.isNullOrEmpty(bankHeader.transCode)) {
            throw new Exception("交易代码为空");
        }
        xmlWriter.writeStartElement("ap");
        xmlWriter.writeElementString("TransCode", bankHeader.transCode);
        xmlWriter.writeElementString("ChannelType", "0");
        xmlWriter.writeElementString("CorpNo", bankFront.org);
        xmlWriter.writeElementString("OpNo", bankFront.operator);
        xmlWriter.writeElementClosed("AuthNo");
        xmlWriter.writeElementString("ReqSeqNo", bankHeader.reqSeqID);
        Date tmpDateNow = new Date();
        xmlWriter.writeElementString("ReqDate", Format.Date8Format.format(tmpDateNow));
        xmlWriter.writeElementString("ReqTime", Format.Time6Format.format(tmpDateNow));
        xmlWriter.writeElementClosed("Sign");
        xmlWriter.writeStartElement("Version");
        xmlWriter.writeElementString("CcVersion", "1");
        xmlWriter.writeEndElement();
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {

        String[] retStr = new String[]{"", ""};

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);

        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);
        String tmpHead = "0" + String.format("%-6d", tmpBytesBody.length);
        byte[] tmpBytesHead = tmpHead.getBytes(tmpCharset);

        byte[] tmpBytesSend = new byte[tmpBytesHead.length + tmpBytesBody.length];
        System.arraycopy(tmpBytesHead, 0, tmpBytesSend, 0, tmpBytesHead.length);
        System.arraycopy(tmpBytesBody, 0, tmpBytesSend, tmpBytesHead.length, tmpBytesBody.length);

        if (isNeedHiddleField) {
            WriteBankLogStep2(FieldHiddenUtil.amountHiddle(tmpHead + p_reqStr, new String[]{"Amt", "批交易总金额"}));
        } else {
            WriteBankLogStep2(tmpHead + p_reqStr);
        }
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesSend);
        if (StringHelper.isNullOrEmpty(tmpReceiver.connState)) {
            String tmpBkStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
            if (isNeedHiddleField) {
                WriteBankLogStep3(FieldHiddenUtil.amountHiddle(tmpBkStr, new String[]{"成功金额", "失败金额", "异常金额", "落地金额"}));
            } else {
                WriteBankLogStep3(tmpBkStr);
            }
        }
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.isCompleted) {
            retStr[1] = new String(tmpReceiver.recBytes, tmpReceiver.contentStartIndex, tmpReceiver.contentLength, tmpCharset);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
            WriteBankLogLn(retStr[1]);
        }
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 7) {
                String tmpHead = new String(p_receiver.recBytes, 1, 6, getCharset());
                p_receiver.contentLength = Integer.parseInt(tmpHead.trim());
                p_receiver.contentStartIndex = 7;
            }
        }
    }

    /*
    int spaceLength = 60 - p_reqBat.readedDetail.recName.getBytes("GBK").length;
    String spaces = "";
                    if (spaceLength >= 0) {
        spaces = String.format("%" + spaceLength + "s", " ");
        tmpSbData.append(p_reqBat.readedDetail.recName).append(spaces);
    } else {
        StringBuilder newName = new StringBuilder(p_reqBat.readedDetail.recName);
        while (newName.toString().getBytes("GBK").length > 60) {
            newName.substring(0, newName.length() - 1);
        }
        tmpSbData.append(newName);
    }
    */
    public String fixedLenCompleSpace(int length, String str, boolean fixLength) {
        int spaceLength = 0;
        String spaces = "";
        try {
            if (length > 0) {
                spaceLength = length - str.getBytes(getCharset()).length;
                if (spaceLength > 0) {
                    spaces = String.format("%" + spaceLength + "s", " ");
                    str += spaces;
                } else if (str.getBytes(getCharset()).length >= length && fixLength) {
                    str = str.substring(0, length - 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
